import * as Koa from 'koa';
import { IDownloadType } from '../kalendjs-type';
import { Exceptions } from '../kalend'
class result {
    /**
     *
     */
    constructor(code: Number, message: String, data: any, errcode?: String) {
        this.code = code;
        this.message = message;
        if (data) {
            this.data = data;
        }
        if (errcode) {
            this.errcode = errcode;
        }
    }
    code: Number;
    message: String;
    data: any;
    errcode: String;
}

export function fail(message: String, errcode?: String | Number, data: any = null) {
    if (errcode) {
        return new result(0, message, data, errcode.toString());
    } else {
        return new result(0, message, data);
    }
}

export function success(data: any, message: String = null) {
    if (data && data.constructor && data.constructor.name === 'Promise') {
        throw Exceptions.known('结果不能是 Promise 类型')
    }
    return new result(1, message || "成功获取数据", data);
}

export function response(ctx: Koa.Context, data: any, code: number = 1, message: String = undefined) {
    // ctx.response.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    // ctx.response.set("Access-Control-Allow-Origin", "*");
    ctx.response.set("Access-Control-Allow-Origin", "*");
    if (code === 1) {
        ctx.body = success(data, message);
    } else {
        ctx.body = fail(message, 40000);
    }
}
export function download(ctx: Koa.Context, data: IDownloadType) {
    ctx.body = data.body.toJSON();
    ctx.response.set("Content-Type", data.contentType || "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    ctx.response.set("Access-Control-Allow-Origin", "*");
    let fileName = data.filename;
    if (fileName) {
        fileName = fileName.trim();
        if (fileName[0] === '.') {
            fileName = '未命名' + fileName;
        }
    } else {
        fileName = "unknown";
    }
    ctx.attachment(fileName);
}

export function image(ctx: Koa.Context, data: IDownloadType, contentType: string = 'image/png') {
    ctx.body = data.body;
    ctx.response.set("Content-Type", contentType);
    ctx.response.set("Access-Control-Allow-Origin", "*");
    ctx.attachment(encodeURI(data.filename));
}

export function downloadfile(ctx: Koa.Context, data: IDownloadType,contentType: string = 'application/octet-stream') {
    ctx.body = data.body;
    ctx.response.set("Access-Control-Allow-Origin", "*");
    ctx.response.set("Content-Type", contentType);
    ctx.attachment(encodeURI(data.filename));
}